# Copyright 2013 Lukas Kemmer
#
# Licensed under the Apache License, Version 2.0 (the "License"); you
# may not use this file except in compliance with the License. You
# may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied. See the License for the specific language governing
# permissions and limitations under the License.

"""Generate build_info.cpp with version constants, dates etc.

"""

import datetime
import os
from locale import getpreferredencoding
from subprocess import Popen, PIPE

def working_copy_modified(wc_path):
    return not _get_svn_revision(wc_path).isdigit()


def _get_svn_revision(wc_path):
    svn_ver = Popen(['svnversion', wc_path], stdout=PIPE)
    return svn_ver.communicate()[0].decode(getpreferredencoding()).rstrip()


def _get_svn_path_line(info_string):
    for line in info_string.split("\n"):
        if line.startswith("URL: "):
            return line[4:].strip()


def _get_svn_path(wc_path):
    svn_info = Popen(['svn', 'info', wc_path], stdout=PIPE)
    return _get_svn_path_line(svn_info.communicate()[0].decode(getpreferredencoding()))


def _now_utc():
    return datetime.datetime.utcnow().strftime("%Y-%m-%d %H:%M UTC")


def _write_string_func( f, name, value ):
    f.write('\n')
    f.write('faint::utf8_string %s(){\n' % name)
    f.write('  return "%s";\n' % value)
    f.write('}\n')


def run(faint_root, version):
    generated_dir = os.path.join(faint_root, "generated")
    if not os.path.exists(generated_dir):
        os.mkdir(generated_dir)

    cpp_path = os.path.join(generated_dir, "build-info.cpp")
    f = open(cpp_path, 'w')
    f.write('// Generated by %s\n' % os.path.basename(__file__))
    f.write('#include "text/utf8-string.hh"\n')
    f.write('namespace faint{\n\n')
    _write_string_func(f, 'faint_version', version)
    _write_string_func(f, 'faint_build_date', _now_utc())
    _write_string_func(f, 'faint_svn_path', _get_svn_path(faint_root))
    _write_string_func(f, 'faint_svn_revision', _get_svn_revision(faint_root))
    f.write('} // namespace\n')
    f.close()
    return cpp_path
